﻿var express = require('express');
var url = require('url');
var bodyParser = require('body-parser');
var path = require('path'); //系统路径模块
var app = express();
var  cheerio = require("cheerio")
var {createToken} = require('./utils/jwt')
var {verifyToken} = require('./utils/jwt')
var querystring = require('querystring');
var sql = require('./utils/sqlUitls')
var log = require('./utils/log')
const axios = require('axios');
var request = require('request');
var fs = require('fs');
var myaxios = require('./utils/myaxios');
var config = require('./bin/config');
const { json } = require('body-parser');
var https = require('https')

app.use(bodyParser.urlencoded({limit: "20mb", extended: false }));
 app.use(bodyParser.json({ limit: "20mb" }));

//设置跨域访问
app.all('*', (req, res, next) => {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header("X-Powered-By", ' 3.2.1');
	res.header("Content-Type", "application/json;charset=utf-8");
	next();
});

const httpsOption = {
	key: fs.readFileSync("./https/5667378_www.daizhongdai.xyz.key"),
	cert: fs.readFileSync("./https/5667378_www.daizhongdai.xyz.pem")
}
https.createServer(httpsOption, app).listen(config.httpsServicePort, () => {

	var host = config.serverHost;
	var port = config.httpsServicePort;
	console.log('Example app https listening at http://%s:%s', host, port);
});

// 配置服务端口
var server = app.listen(config.port, function () {
	var host = config.serverHost;
	var port = config.serverPort;
	console.log('Example app listening at http://%s:%s', host, port);
})
// var server = app.listen(3000,"0.0.0.0");



var datainfo = {
	RESULT: "S",
	ERRMSG: "成功",
	code: 200,
	data:{},
	token:""
}

// function datainfo(res,ress) {
// 	//成功返回
// 	var successInfo = {
// 		RESULT: "S",
// 		ERRMSG: "成功",
// 		code: 200,
// 		data:res.json(ress)
// 	}
// }
//失败返回
//失败返回
var errors = {
	RESULT: "F",
	ERRMSG: "失败",
	code: 204,
	data:{},
	token:""
}

const apikey = config.apikey
const secretkey = config.secretkey
//1. 获取key
var accessId = "24.92d6edb9ab8ecd4c92c111d21c5fb829.2592000.1623846197.282335-24189221"
async function getKey() {
	let keyInfo = await axios({
		url: 'http://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + apikey + '&client_secret=' + secretkey,
	})
	accessId = keyInfo.data.access_token
	console.log("keyInfo"+accessId);
}

getKey()




app.get("/",(req,res)=>{
	res.send("hello wolrd");
})

//2.识别果蔬类食材
app.post("/getApple", (req, res) => {
	
	var body = req.body
	console.log(body);
	myaxios.request({
		url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient?access_token=' + accessId,
		
		method: 'POST',
		header: { "Content-Type": "application/x-www-form-urlencoded" },
		data: {
			"image":body.image,
			"url": body.url
		}
	}).then(ress=>{
		console.log(ress.data);
		res.json(ress.data)
		res.status(200)
		res.end()
	})

})


//3.识别菜品
app.post("/getDish", (req, res) => {
	var body = req.body
	console.log(body);
	myaxios.request({
		url: 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=' + accessId,
		method: 'POST',
		header: { "Content-Type": "application/x-www-form-urlencoded" },
		data: {
			"image":body.image,
			"url": body.url
		}
	}).then(ress=>{
		console.log(ress.data);
		res.json(ress.data)
		res.status(200)
		res.end()
	})
})

//根据名字查 热量等数据
app.get('/getserch',(req,res)=>{
	// 多条件查询，动态拼接sql
	var sqlstr = 'select * from eatdata where  1=1'
	var params = url.parse(req.url, true).query;
	if (params.name !== undefined) sqlstr = sqlstr + " and name= '" + params.name + "'"
	
	var offset = params.offset ===undefined ?20:params.offset
	var num = params.pageNum ===undefined? 0:params.pageNum*offset
	sql.select(sqlstr + " limit "+num+"," +offset,{"tableName":"eatdata"})
	.then(ress=>{

		// console.log(ress);
		res.json(ress)
		res.status(200)
		res.end()
	})

})




//根据名字数据
app.get('/getInfo',(req,res)=>{
	// 多条件查询，动态拼接sql
	var sqlstr = 'select * from caipu_1 where  1=1'
	var params = url.parse(req.url, true).query;
	if (params.name !== undefined) sqlstr = sqlstr + " and name= '" + params.name + "'"
	if (params.id !== undefined) sqlstr = sqlstr + " and id= '" + params.id + "'"
     // 按照菜单分类
	if (params.category !== undefined) sqlstr = sqlstr + " and cid= '" + params.cid + "'"

	
	
	var offset = params.offset ===undefined ?20:params.offset
	var num = params.pageNum ===undefined? 0:params.pageNum*offset
	sql.select(sqlstr + " limit "+num+"," +offset,{"tableName":"caipu_1"})
	.then(ress=>{
		// console.log(ress);
		res.json(ress)
		res.status(200)
		res.end()
	})

})

//首页推荐
app.get('/index/tj',(req,res)=>{
// console.log(Math.ceil(Math.random()*20));
   var sqlstr = 'select * from caipu_1 LIMIT  '+Math.ceil(Math.random()*35)+","+Math.ceil(Math.random()*50);
   sql.select(sqlstr).then(ress=>{
	datainfo.data = ress
	res.json(datainfo)
	res.status(200)
	res.end()
   })
})



//4.多条件查询
app.get('/classify',(req,res)=>{
	// 多条件查询，动态拼接sql
	var sqlstr = 'select * from caipu_1 where  1=1';
	var params = url.parse(req.url, true).query;
	if (params.name !== undefined) sqlstr = sqlstr + " and title= '" + params.name + "'"
	if (params.cid !== undefined) sqlstr = sqlstr + " and cid like " +"'%"+ params.cid + "%'"
	if (params.zid !== undefined) sqlstr = sqlstr + " and zid= '" + params.zid + "'"

	var offset = params.offset ===undefined ?20:params.offset
	var num = params.pageNum ===undefined? 0:params.pageNum*offset
	sql.select(sqlstr + " limit "+num+"," +offset,{"tableName":"caipu_1"})
	.then(ress=>{
		// console.log(ress);
	   datainfo.data = ress
	    res.json(datainfo)
		res.status(200)
		res.end()
	})

})
//4.搜索模糊查询
app.get('/like/query',(req,res)=>{
	// 多条件查询，动态拼接sql
	var sqlstr = 'select * from caipu_1 where  1=1';
	var params = url.parse(req.url, true).query;
	if (params.name !== undefined) sqlstr = sqlstr + " and title like " +"'%"+ params.name + "%'" +"ORDER BY caipu_1.favnum desc"

	
	var offset = params.offset ===undefined ?20:params.offset
	var num = params.pageNum ===undefined? 0:params.pageNum*offset
	sql.select(sqlstr + " limit "+num+"," +offset,{"tableName":"caipu_1"})
	.then(ress=>{
		// console.log(ress);
	   datainfo.data = ress
	    res.json(datainfo)
		res.status(200)
		res.end()
	})

})




//登录接口
app.get('/login',function (req,res,next) {
	console.log("this is code"+ req.query.code);
	var data = {
	  'appid':'wx40466c078a18fd65',
	  'secret':'b30931d8bef38e33a38fba33d8d4a1e1',
	  'js_code':req.query.code,
	  'grant-type':'authorization_code'
	};
	console.log(data);
	var content = querystring.stringify(data);
	var urls = 'https://api.weixin.qq.com/sns/jscode2session?'+content;
	request.get({
	  'url':urls
	},(error,response,body) => {
	  //将body的内容解析出来
	   result = JSON.parse(body);
	  result.code = req.query.code;
	  console.log("OPenid"+result.openid);
	  console.log(result);
	
	//   var params = url.parse(req.url, true).query;
	//    查询是否有该用户 没有就插入

	 sql.getcount(result.openid).then(ress=>{
		 console.log(ress.data[0]);
		 for (var i in ress.data[0]) {
			if(ress.data[0][i]===1){
				datainfo_success={
					RESULT: "S",
					ERRMSG: "成功",
					code: 200,
isNew:false,
					token:{}
				}
				var tokenor = {username: result.openid}
				datainfo_success.token=createToken(tokenor)
				res.json(datainfo_success)
				res.status(200)
				res.end()
			}else if(ress.data[0][i]===0){

	//   用户信息存入
	  var params = url.parse(req.url,true).query;
	  sql.insert(res, next,params,result.openid).then(ress=>{
		var tokenor = {username: result.openid}
		datainfo.data=ress
		datainfo.token=createToken(tokenor)
 datainfo.isNew = true
	   res.json(datainfo)
	   res.status(200)
	   res.end()
	  })
			}else{
		   console.log(errors);
			res.json(errors)
			res.status(200)
			res.end()
			}
        }
	 })



	//   res.json(result)
	
	})

   });

//完善我的信息
app.get('/profect_info',function (req,res,next) {  
		  var params = url.parse(req.url,true).query;
		  var token=req.headers.sessiontoken
		  // 校验token decode指解码后的信息
		  let decode = verifyToken(token)
		  console.log(decode.username);
		  sql.profect(res, next,params,decode.username).then(ress=>{
		   res.json(ress)
		   res.status(200)
		   res.end()
		  })
})


//检查token是否过期
app.post('/user_list', function (req, res, next) {
	var token=req.headers.sessiontoken // 获取前端请求头发送过来的tokenid()
	if (token) {
			// 校验token decode指解码后的信息
			let decode = verifyToken(token)
			console.log(decode.username);
			datainfo.open_id="";
			datainfo.token=decode.username
			res.json(datainfo)
			res.status(200)
			res.end()	  
			
			
	}
	else {
			res.json(errors)
		res.status(200)
		res.end()	  
		
	}

  
})

//添加收藏
app.get('/collect', (req,res) =>{
	var params = url.parse(req.url,true).query;
	var token=req.headers.sessiontoken
	// 校验token decode指解码后的信息
	let decode = verifyToken(token)
	console.log(decode.username);
	sql.collect(res,params,decode.username).then(ress=>{
	 res.json(ress)
	 console.log(ress);
	 res.status(200)
	 res.end()
	})
})

//获取收藏列表
app.get('/getcollectinfo',(req,res)=>{
	var params = url.parse(req.url,true).query;
	var token=req.headers.sessiontoken
	// 校验token decode指解码后的信息
	let decode = verifyToken(token)
	console.log(decode.username);

	var sqlstr = "SELECT * FROM sz_menus where 1=1" + " and open_id= '" + decode.username + "'";
	// if (req.headers.sessiontoken !== undefined) sqlstr = sqlstr + " and open_id= '" + decode.username + "'"

	var offset = params.offset ===undefined ?20:params.offset
	var num = params.pageNum ===undefined? 0:params.pageNum*offset
	sql.select(sqlstr,{"tableName":"sz_menus"})
	.then(ress=>{
		// console.log(ress);
		datainfo.data = ress
		console.log(ress);
	    res.json(datainfo)
		res.status(200)
		res.end()
	})
})
//删除收藏
//app.get('/deleteinfo',(req,res)=>{
//	 var params = url.parse(req.url,true).query;
//	 var token=req.headers.sessiontoken
	 // 校验token decode指解码后的信息
//	 let decode = verifyToken(token)
//	 console.log(decode.username);
	// sql.delcollect(res,decode.username).then(ress=>{
	// res.json(ress)
	// console.log(ress);
	// res.status(200)
	// res.end()
	//})
//})


//添加扫描
app.get('/insert/scann', (req,res) =>{
	var params = url.parse(req.url,true).query;
	var token=req.headers.sessiontoken
	// 校验token decode指解码后的信息
	let decode = verifyToken(token)
	console.log(decode.username);
	sql.scann(res,params,decode.username).then(ress=>{
	 res.json(ress)
	 console.log(ress);
	 res.status(200)
	 res.end()
	})
})

//删除记录
app.get('/del/scann',(req,res)=>{
	var params = url.parse(req.url,true).query;
	var token=req.headers.sessiontoken
	// 校验token decode指解码后的信息
	let decode = verifyToken(token)
	console.log(decode.username);
	sql.delscann(res,decode.username).then(ress=>{
	res.json(ress)
	console.log(ress);
	res.status(200)
	res.end()
   })
})



//获取扫描列表
app.get('/getscaninfo',(req,res)=>{
	var params = url.parse(req.url,true).query;
	var token=req.headers.sessiontoken
	// 校验token decode指解码后的信息
	let decode = verifyToken(token)
	console.log(decode.username);

	var sqlstr = "SELECT * FROM scan where 1=1" + " and open_id= '" + decode.username + "'";
	// if (req.headers.sessiontoken !== undefined) sqlstr = sqlstr + " and open_id= '" + decode.username + "'"

	var offset = params.offset ===undefined ?20:params.offset
	var num = params.pageNum ===undefined? 0:params.pageNum*offset
	sql.select(sqlstr,{"tableName":"scan"})
	.then(ress=>{
		// console.log(ress);
		datainfo.data = ress
		console.log(ress);
	    res.json(datainfo)
		res.status(200)
		res.end()
	})
})






//7.8补充

function getP(req) {
	return url.parse(req.url, true).query;
}

var sql2 = require('./utils/sqlUitls2')
app.get('/getDishDetail',(req,res)=>{
	var t = getP(req)
	sql2.select("select * from sheet1 where name = '" +t.name+"'")
	.then(ress=>{
		console.log(ress);
		if(ress.data.length==0){
			sql2.select("select * from sheet1 where name like '%" +t.name+"%'")
			.then(resss=>{
				datainfo.data = resss
				res.json(datainfo)
				res.end()
			}).catch(err=>{
				console.log(err);
				errors.data = err
				res.json(errors)
				res.end()
			})
			
			return
		}
		datainfo.data = ress
		res.json(datainfo)
		res.end()
	}).catch(err=>{
		console.log(err);
		errors.data = err
		res.json(errors)
		res.end()
	})
})



//删除收藏
app.get('/deleteinfo',(req,res)=>{
 

	var params = url.parse(req.url, true).query;

		console.log(params.id);
		sql.delcollect(res,params.id).then(ress=>{
		res.json(ress)
		console.log(ress);
		res.status(200)
		res.end()
	   })



	
})


//添加扫描
app.get('/insert/scann', (req,res) =>{
	var params = url.parse(req.url,true).query;
	var token=req.headers.sessiontoken
	// 校验token decode指解码后的信息
	let decode = verifyToken(token)
	console.log(decode.username);
	sql.scann(res,params,decode.username).then(ress=>{
	 res.json(ress)
	 console.log(ress);
	 res.status(200)
	 res.end()
	})
})

//删除扫描
app.get('/del/scann',(req,res)=>{
	
	var params = url.parse(req.url, true).query;
	console.log(params.id);
	sql.delscann(res,params.id).then(ress=>{
	res.json(ress)
	console.log(ress);
	res.status(200)
	res.end()
   })
})

//添加收藏
app.get('/collect', (req,res) =>{
	var params = url.parse(req.url,true).query;
	var token=req.headers.sessiontoken
	// 校验token decode指解码后的信息
	let decode = verifyToken(token)
	console.log(decode.username);
	sql.collect(res,params,decode.username).then(ress=>{
	 res.json(ress)
	 console.log(ress);
	 res.status(200)
	 res.end()
	})
})

//用户补充完善信息
app.get('/perfect/user', (req,res) =>{

	var params = url.parse(req.url,true).query;
console.log(params )
	var token=req.headers.sessiontoken
	// 校验token decode指解码后的信息
	let decode = verifyToken(token)
	console.log(decode.username);
	sql.updateuserchoice(res,params,decode.username).then(ress=>{
	 res.json(ress)
	 console.log(ress);
	 res.status(200)
	 res.end()
	})
})


//扫描食物微量元素数据
app.get('/getscanfood',(req,res)=>{
	var params = url.parse(req.url,true).query;

	var sqlstr = "SELECT * FROM scanfood where 1=1";
	if (params.name !== undefined) sqlstr = sqlstr + " and name= '" + params.name + "'"
	

	var offset = params.offset ===undefined ?20:params.offset
	var num = params.pageNum ===undefined? 0:params.pageNum*offset
	sql.select(sqlstr,{"tableName":"scanfood"})
	.then(ress=>{
		// console.log(ress);
		datainfo.data = ress
		console.log(ress);
	    res.json(datainfo)
		res.status(200)
		res.end()
	})
})
//扫描食物相克食物
app.get('/scanreversefood',(req,res)=>{
	var params = url.parse(req.url,true).query;

	var sqlstr = "SELECT * FROM tb_course where 1=1";
	if (params.name !== undefined) sqlstr = sqlstr + " and courseNo= '" + params.name + "'"
	

	var offset = params.offset ===undefined ?20:params.offset
	var num = params.pageNum ===undefined? 0:params.pageNum*offset
	sql.select(sqlstr,{"tableName":"tb_course"})
	.then(ress=>{
		// console.log(ress);
		datainfo.data = ress
		console.log(ress);
	    res.json(datainfo)
		res.status(200)
		res.end()
	})
})


//获取我的信息
app.get('/getuserinfo',function (req,res,next) {  
	var sqlstr = 'select * from user where  1=1';
	var token=req.headers.sessiontoken
	// 校验token decode指解码后的信息
	let decode = verifyToken(token)
	console.log(decode.username);
	if (decode.username !== undefined) sqlstr = sqlstr + " and open_id = '"+ decode.username+"'"

	

	sql.select(sqlstr)
	.then(ress=>{

	   datainfo.data = ress
	    res.json(datainfo)
		res.status(200)
		res.end()
	})
})


//机器人
app.get('/robot', (req, res) => {
	let p = getP(req)
	if(p.query==undefined||p.id==undefined){
		errors.data = '请输入完整参数'
		res.json(errors)
		res.end()
		return
	}
	axios.post('https://aip.baidubce.com/rpc/2.0/unit/bot/chat?access_token=24.0c0f3adcb0f29f4a7bac4c2f8316b1c8.2592000.1628683203.282335-24536086',
	{
		"version":"2.0",
		"bot_id":"1107537",
		"log_id":p.id,
		"request": {
			"user_id":p.id,
			"query":p.query,
			"query_info":{
				"type":"TEXT",
				"source":"KEYBOARD"
			},
			"bernard_level":1,
			"session_id":p.id
		}
	
	})
		.then(ress => {
			console.log(ress.data)
			datainfo.data = ress.data
			res.json(datainfo)
			res.end()
		})
		.catch(err => {
			console.error(err);
			errors.data = err
			res.json(errors)
			res.end()
		})
})